export module SchoolDataBaseTest;

import std;
import IIS_push_str;
import "IIS_push_str.hpp";
import <boost/json.hpp>;
import JsonAxios;

import SchoolDataBaseTestStruct;

using namespace boost;

GetMapper("/apicpp/test1") {
	std::cout << "GetMapper: /apicpp/test1 -> " << req_body << std::endl;
	std::vector<json::object> vec_get;
	for (const auto& item : SchoolDataBaseTestStruct::testData) {
		vec_get.push_back(item.to_json());
	}
	return json::serialize(JsonAxios::res_200_arr(vec_get));
}

PostMapper("/apicpp/test1") {
	std::cout << "PostMapper: /apicpp/test1 -> " << req_body << std::endl;
	json::object new_item_obj = json::parse(req_body).as_object();
	SchoolDataBaseTestStruct::Test new_item(new_item_obj);
	auto begin = SchoolDataBaseTestStruct::testData.begin();
	auto end = SchoolDataBaseTestStruct::testData.end();
	auto it = std::find(begin, end, new_item);
	if (it == end) {
		throw std::runtime_error("PostMapper: /apicpp/test1 -> Item not found in vector");
	}
	SchoolDataBaseTestStruct::testData.erase(it);
	return JsonAxios::res_200_null;
}

PutMapper("/apicpp/test1") {
	std::cout << "PutMapper: /apicpp/test1 -> " << req_body << std::endl;
	json::object json = json::parse(req_body).as_object();
	json::object old_item_obj = json.at("old").as_object();
	json::object new_item_obj = json.at("new").as_object();

	SchoolDataBaseTestStruct::Test old_item(old_item_obj);
	auto begin = SchoolDataBaseTestStruct::testData.begin();
	auto end = SchoolDataBaseTestStruct::testData.end();
	auto it = std::find(begin, end, old_item);
	if (it == end) {
		SchoolDataBaseTestStruct::testData.push_back(new_item_obj);
	}
	else {
		*it = SchoolDataBaseTestStruct::Test(new_item_obj);
	}
	return JsonAxios::res_200_null;
}